package com.ls.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ls.config.satoken.SaTokenUtilPy;
import com.ls.controller.phonerecord.model.QueryPhoneRecordModel;
import com.ls.entity.Customer;
import com.ls.entity.FeedbackRecord;
import com.ls.entity.PhoneRecord;
import com.ls.mapper.PhoneRecordMapper;
import com.ls.service.IPhoneRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.utils.ResultData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.ls.constant.SystemConstants.*;

/**
 * <p>
 * 通话记录表 服务实现类
 * </p>
 *
 * @author pengyu
 * @since 2024-10-13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PhoneRecordServiceImpl extends ServiceImpl<PhoneRecordMapper, PhoneRecord> implements IPhoneRecordService {
    /** 通话记录统计 */
    @Override
    public ResultData getList(QueryPhoneRecordModel model){
//        // 获取当前用户ID
        Long customerId = SaTokenUtilPy.getCustomer().getCustomerId();
        // 当前查询时间段
        LocalDateTime currentStart = LocalDate.parse(model.getBeginSt())
                .atStartOfDay();
        LocalDateTime currentEnd = LocalDate.parse(model.getEndSt())
                .atTime(23, 59, 59);
        long daysBetween = ChronoUnit.DAYS.between(currentStart, currentEnd);

        // 构建当前周期查询条件
        LambdaQueryWrapper<PhoneRecord> currentWrapper = new LambdaQueryWrapper<PhoneRecord>()
                .eq(PhoneRecord::getCustomerId, customerId)
                .between(PhoneRecord::getStartTime, currentStart, currentEnd);

        // 统计当前周期数据
        long currentIncoming = count(currentWrapper.clone().eq(PhoneRecord::getCallType, CALL_STATUS_RECEIVE));
        long currentOutgoing = count(currentWrapper.clone().eq(PhoneRecord::getCallType, CALL_STATUS_OUT_REJECT));
        long currentMissed = count(currentWrapper.clone().eq(PhoneRecord::getCallType, CALL_STATUS_NOT_RECEIVE));
        long currentTotal = count(currentWrapper);

        // 计算对比周期（前一周）
        LocalDateTime compareStart = currentStart.minusDays(daysBetween + 1);
        LocalDateTime compareEnd = currentEnd.minusDays(daysBetween + 1);

        // 统计对比周期数据
        LambdaQueryWrapper<PhoneRecord> compareWrapper = new LambdaQueryWrapper<PhoneRecord>()
                .eq(PhoneRecord::getCustomerId, customerId)
                .between(PhoneRecord::getStartTime, compareStart, compareEnd);

        long compareIncoming = count(compareWrapper.clone().eq(PhoneRecord::getCallType, CALL_STATUS_RECEIVE));
        long compareOutgoing = count(compareWrapper.clone().eq(PhoneRecord::getCallType, CALL_STATUS_OUT_REJECT));
        long compareMissed = count(compareWrapper.clone().eq(PhoneRecord::getCallType, CALL_STATUS_NOT_RECEIVE));
        long compareTotal = count(compareWrapper);

        // 构建返回数据结构
        Map<String, Object> result = new LinkedHashMap<>();

        // 通话总览
        Map<String, Object> overview = new LinkedHashMap<>();
        overview.put("接入电话", buildStats(currentIncoming, calculateRatio(currentIncoming, compareIncoming)));
        overview.put("拨出电话", buildStats(currentOutgoing, calculateRatio(currentOutgoing, compareOutgoing)));
        overview.put("漏接电话", buildStats(currentMissed, calculateRatio(currentMissed, compareMissed)));
        overview.put("总通话次数", buildStats(currentTotal, calculateRatio(currentTotal, compareTotal)));
        result.put("通话总览", overview);

        // 接入次数排行
        List<Map<String, Object>> rankList = baseMapper.selectCallRank(
                customerId,
                currentStart,
                currentEnd,
                8
        );
        result.put("接入次数排行", rankList);

        return ResultData.successData(result);
    }

    // 环比计算逻辑（处理除零情况）
    private double calculateRatio(long current, long compare) {
        if (compare == 0) return current == 0 ? 0.0 : 100.0;
        return ((current - compare) * 100.0) / compare;
    }

    // 统计项构建方法
    private Map<String, Object> buildStats(long count, double ratio) {
        String trend = ratio != 0 ? (ratio > 0 ? "↑" : "↓") : "";
        return new LinkedHashMap<String, Object>() {{
            put("数量", count);
            put("环比", String.format("%.1f%% %s", Math.abs(ratio), trend));
        }};
    }
}
